package com.hnucm.chapter5_2;

import androidx.appcompat.app.AppCompatActivity;

import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.hnucm.chapter5_2.utils.MyConstants;
import com.hnucm.chapter5_2.utils.ProcessUtil;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private LinearLayout mRemoteViewsContent;

    private BroadcastReceiver mRemoteViewsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            RemoteViews remoteViews = intent
                    .getParcelableExtra(MyConstants.EXTRA_REMOTE_VIEWS);
            if (remoteViews != null) {
                updateUI(remoteViews);

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(MainActivity.this, ProcessUtil.getCurrentProcessNameByApplication(),Toast.LENGTH_SHORT).show();
        initView();
    }

    private void initView() {
        mRemoteViewsContent = (LinearLayout) findViewById(R.id.remote_views_content);
        IntentFilter filter = new IntentFilter(MyConstants.REMOTE_ACTION);
        registerReceiver(mRemoteViewsReceiver, filter);
        TextView textView=findViewById(R.id.button1);
        textView.setText("process:"+Process.myPid()+"");
    }

    private void updateUI(RemoteViews remoteViews) {
        View view = remoteViews.apply(getApplicationContext(), mRemoteViewsContent);
//        int layoutId = getResources().getIdentifier("layout_notification", "layout", getPackageName());
//        View view = getLayoutInflater().inflate(layoutId, mRemoteViewsContent, false);
//        remoteViews.reapply(getApplicationContext(), view);
        mRemoteViewsContent.addView(view);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mRemoteViewsReceiver);
        super.onDestroy();
    }

    public void onButtonClick(View v) {
        if (v.getId() == R.id.button1) {
            Intent intent = new Intent(this, BaseActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.button2) {
            //BaseActivity不停的发送通知消息
            Intent intent = new Intent(this, BaseActivity.class);
            startActivity(intent);
        }
    }
}